/*
 * @Author: HZK
 * @Date: 2020-08-24 18:43:16
 * @LastEditTime: 2020-08-25 14:23:43
 * @LastEditors: hanfengmi
 * @Description: 手写promise
 * 
 */

// 手写promise
// 实现promise每一个api


const PENDING = 'pending'
const FULLLFILLED = 'fullfilled'
const REJECTED = 'rejected'
class MyPromise {
    constructor(executor){
        try{
            executor(this.resolve, this.reject)
        }catch(e){
            this.reject(e)
        }
    }
    status = PENDING;
    // 成功的值
    value = undefined;
    // 失败的原因
    reason = undefined;
    // 成功回调 存储多个
    successCallback = []
    // 失败回调
    failCallback = []
    // 箭头函数是考虑的this指向
    resolve = value => {
        // 状态判断
        if(this.status !== PENDING) return
        // 将状态修改为完成
        this.status = FULLLFILLED
        // 保存成功的值
        this.value = value
        while(this.successCallback.length) {
            this.successCallback.shift()()
        }
    }
    reject = reason => {
        // 状态判断
        if(this.status !== PENDING) return
        // 将状态修改为完成
        this.status = REJECTED
        // 保存失败的原因
        this.reason = reason
        while(this.failCallback.length) {
            this.failCallback.shift()()
        }
    }
    then (successCallback,failCallback) {
        // then方法参数选填（不传参数）
        successCallback = successCallback ? successCallback : value=>value
        failCallback = failCallback ? failCallback : reason => {throw reason}
        // 链式调用
        let promise2 = new MyPromise((resolve,reject)=>{
            // 状态判断
            if(this.status === FULLLFILLED){
                setTimeout(()=>{// 异步代码执行，为了获取promise2
                    try{// 捕获异常
                        let x = successCallback(this.value)
                        // 判断x的状态（普通值 || promise）
                        // resolve(x)// 传递给下个promise
                        resolvePromise(promise2, x,resolve,reject)
                    }catch(e){
                        reject(e)
                    }
                },0)
            }else if(this.status === REJECTED){
                setTimeout(()=>{// 异步代码执行，为了获取promise2
                    try{// 捕获异常
                        let x = failCallback(this.reason)
                        // 判断x的状态（普通值？promise）
                        // resolve(x)// 传递给下个promise
                        resolvePromise(promise2, x,resolve,reject)
                    }catch(e){
                        reject(e)
                    }
                },0)
            }else {// 等待状态，需要存储回调函数
                this.successCallback.push(()=>{
                    setTimeout(()=>{// 异步代码执行，为了获取promise2
                        try{// 捕获异常
                            let x = successCallback(this.value)
                            // 判断x的状态（普通值？promise）
                            // resolve(x)// 传递给下个promise
                            resolvePromise(promise2, x,resolve,reject)
                        }catch(e){
                            reject(e)
                        }
                    },0)
                });
                this.failCallback.push(()=>{
                    setTimeout(()=>{// 异步代码执行，为了获取promise2
                        try{// 捕获异常
                            let x = failCallback(this.reason)
                            // 判断x的状态（普通值？promise）
                            // resolve(x)// 传递给下个promise
                            resolvePromise(promise2, x,resolve,reject)
                        }catch(e){
                            reject(e)
                        }
                    },0)
                });
            }
        });
        // 自己返回自己的错误判断
        return promise2;
    }  
    
    finally(callback){
        return this.then((value)=>{
            return MyPromise.resolve(callback()).then(()=>value);
        },(reson)=>{
            callback()
            return MyPromise.resolve(callback()).then(()=>{throw reson});
        })
    }

    catch(failCallback){
        return this.then(undefined,failCallback)
    }

    static all (array) {
        // 静态方法
        // 返回promise
        // 顺序执行
        let result = [];
        let index = 0;
        return new MyPromise((resolve,reject)=>{
            function addData(key,value){
                result[key] = value;
                index++;
                if(index === array.length){
                    resolve(result)
                }
            }
            for (let i = 0; i < array.length; i++) {
                let current = array[i];
                if(current instanceof MyPromise){
                    current.then(value => addData(i,value),reson=>reject(reson))  
                }else {// 普通值
                    addData(i,array[i])
                }
            }
        })

    }

    static resolve(value){
        if(value instanceof MyPromise) return value;
        return new MyPromise((resolve)=> resolve(value))
    }
}

function resolvePromise(promise2, x, resolve, reject) {
    if(promise2 === x){
        return reject(new Error('错误啦'))
    }
    if(x instanceof MyPromise){ //是promise
        x.then(resolve,reject)
    }else {
        resolve(x)
    }
}
export default MyPromise